# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

from django.contrib.auth.models import AbstractUser, PermissionsMixin

import logging

logger = logging.getLogger("smAdmin")

CHECK_STATUS_CHOICES = (
	(0, "未提交"),
	(1, "待审核"),
	(2, "通过"),
	(3, "驳回"),
)

YES_NO_CHOICES = (
	(0, "否"),
	(1, "是"),
)


class SmadminPermission(models.Model):
	id = models.BigAutoField(primary_key=True)
	codename = models.CharField(unique=True, max_length=100, verbose_name=u"权限代码")
	title = models.CharField(max_length=255, verbose_name=u"标题")
	url = models.CharField(max_length=64, verbose_name=u"权限路径")
	type = models.CharField(max_length=32, verbose_name=u"类型", choices=(("menu", "菜单"), ("submenu", "二级菜单"), ("element", "元素")))
	parent_id = models.IntegerField(verbose_name=u"父Id")
	sort = models.IntegerField(verbose_name=u"排序")
	icon_class = models.CharField(max_length=32, blank=True, null=True, verbose_name=u"菜单图标class")

	class Meta:
		managed = False
		db_table = 'smadmin_permission'


class SmadminRole(models.Model):
	id = models.BigAutoField(primary_key=True)
	name = models.CharField(unique=True, max_length=64, blank=True, null=True, verbose_name=u"角色")

	parent_id = models.BigIntegerField(verbose_name=u"创建者", default=0)

	permissions = models.ManyToManyField(SmadminPermission, related_name="role_set", related_query_name="permission", through='SmadminRolePermission', through_fields=('role', 'permission'))

	class Meta:
		managed = False
		db_table = 'smadmin_role'


class SmadminRolePermission(models.Model):
	id = models.BigAutoField(primary_key=True)

	# role_id = models.BigIntegerField()
	role = models.ForeignKey(SmadminRole, db_column="role_id", related_name="role_set", to_field='id')

	# permission_id = models.BigIntegerField()
	permission = models.ForeignKey(SmadminPermission, db_column="permission_id", related_name="permission_set", to_field='id')

	checked = models.IntegerField()

	class Meta:
		managed = False
		db_table = 'smadmin_role_permission'


class SmAdminUser(AbstractUser, PermissionsMixin):
	username = models.CharField(unique=True, max_length=150, verbose_name=u"用户名")
	password = models.CharField(max_length=128, verbose_name=u"密码")

	# role_id = models.IntegerField()
	role = models.ForeignKey(SmadminRole, db_column="role_id", to_field='id', related_name="user_set", related_query_name="user", verbose_name=u"角色")

	first_name = models.CharField(max_length=30, verbose_name=u"名")
	last_name = models.CharField(max_length=30, verbose_name=u"姓")
	email = models.CharField(max_length=254, verbose_name=u"邮箱")
	is_superuser = models.IntegerField(verbose_name=u"是否超级用户")
	is_staff = models.IntegerField(verbose_name=u"在职状态")
	is_active = models.IntegerField(verbose_name=u"可用状态")
	last_login = models.DateTimeField(blank=True, null=True, verbose_name=u"最后登录时间")
	date_joined = models.DateTimeField(verbose_name=u"创建时间")

	USERNAME_FIELD = 'username'

	class Meta:
		managed = False
		db_table = 'smadmin_user'

	def get_group_permissions(self, obj=None):
		"""
		Returns a list of permission strings that this user has through their
		groups. This method queries all available auth backends. If an object
		is passed in, only permissions matching this object are returned.
		"""
		permissions = set()

		rows = self.role.permissions.all()
		permissions.update(rows)

		logger.info(u"获取组[%s]的所有权限：%s" % (obj, permissions,))

		# for backend in auth.get_backends():
		# 	if hasattr(backend, "get_group_permissions"):
		# 		permissions.update(backend.get_group_permissions(self, obj))

		return permissions

	def get_all_permissions(self, obj=None):
		permissions = set()

		rows = self.role.permissions.all()
		permissions.update(rows)

		logger.info(u"获取obj[%s]的所有权限：%s" % (obj, permissions,))

		return permissions

	def has_perm(self, perm, obj=None):
		""" 校验权限
		:param perm: 权限名
		:param obj:
		:return:
		"""

		# Active superusers have all permissions.
		if self.is_active and self.is_superuser:
			logger.info(u"超级管理员，拥有所有权限：perm[%s]obj[%s]" % (perm, obj,))
			return True

		logger.info(u"检查权限：perm[%s]obj[%s]" % (perm, obj,))

		c = SmadminRolePermission.objects.filter(role_id=self.role_id, permission__codename=perm, checked=1).count()
		if c > 0:
			logger.info(u"用户[%s] 拥有权限[%s]" % (self.username, perm,))
			return True

		logger.info(u"用户[%s] 没有权限p[%s]" % (self.username, perm,))
		return False

	def has_perms(self, perm_list, obj=None):
		"""
		Returns True if the user has each of the specified permissions. If
		object is passed, it checks if the user has all required perms for this
		object.
		"""
		return all(self.has_perm(perm, obj) for perm in perm_list)

	def has_module_perms(self, app_label):
		"""
		Returns True if the user has any permissions in the given app label.
		Uses pretty much the same logic as has_perm, above.
		"""
		# Active superusers have all permissions.
		if self.is_active and self.is_superuser:
			return True
		logger.info(u"检查是否拥有模块权限：app_label[%s]" % (app_label,))
		return True


class SmerpAccount(models.Model):
	id = models.BigAutoField(primary_key=True, verbose_name=u"账号Id")
	email = models.CharField(unique=True, max_length=32, verbose_name=u"账号")
	passwd = models.CharField(max_length=32, verbose_name=u"密码")
	email_vaild = models.IntegerField(choices=YES_NO_CHOICES, verbose_name=u"邮箱是否验证")
	smcode_num = models.BigIntegerField(verbose_name=u"溯源码数量")
	is_active = models.IntegerField(choices=YES_NO_CHOICES, verbose_name=u"是否激活")
	login_ip = models.CharField(max_length=16, verbose_name=u"最后登录IP")
	login_time = models.DateTimeField(blank=True, null=True, verbose_name=u"最后登录时间")
	create_time = models.DateTimeField(blank=True, null=True, verbose_name=u"创建时间")

	class Meta:
		managed = False
		db_table = 'smerp_account'


class SmerpBrand(models.Model):
	id = models.BigAutoField(primary_key=True, verbose_name=u"品牌Id")
	# account_id = models.BigIntegerField()
	smerpaccount = models.ForeignKey(SmerpAccount, db_column="account_id", related_name="smerpbrands", to_field='id')

	name_zh = models.CharField(unique=True, max_length=64, verbose_name=u"品牌名称")
	name_en = models.CharField(max_length=64, blank=True, null=True, verbose_name=u"品牌英文名称")
	logo = models.CharField(max_length=128, blank=True, null=True, verbose_name=u"商标Logo")
	license_img = models.CharField(max_length=200, blank=True, null=True, verbose_name=u"商标注册证书")
	check_status = models.IntegerField(choices=CHECK_STATUS_CHOICES, verbose_name=u"审核状态")
	description = models.CharField(max_length=1024, blank=True, null=True, verbose_name=u"品牌说明")
	create_time = models.DateTimeField(verbose_name=u"创建时间")
	submit_check_time = models.DateTimeField(blank=True, null=True, verbose_name=u"提交审核时间")
	check_mark = models.CharField(max_length=512, blank=True, null=True, verbose_name=u"审核说明")
	check_time = models.DateTimeField(blank=True, null=True, verbose_name=u"审核时间")

	class Meta:
		managed = False
		db_table = 'smerp_brand'


class SmerpBrandLicense(models.Model):
	id = models.BigAutoField(primary_key=True)
	# brand_id = models.BigIntegerField()
	smerpbrand = models.ForeignKey(SmerpBrand, db_column="brand_id", related_name="smerpbrandlicenses", to_field='id')

	name = models.CharField(max_length=32, verbose_name=u"证书名称")
	type = models.CharField(max_length=16, verbose_name=u"证书类型")
	icon = models.CharField(max_length=128, verbose_name=u"证书图标")
	img = models.CharField(max_length=128, verbose_name=u"证书图片")
	description = models.CharField(max_length=1024, verbose_name=u"描述")
	create_time = models.DateTimeField(verbose_name=u"创建时间")

	class Meta:
		managed = False
		db_table = 'smerp_brand_license'


class SmerpErpinfo(models.Model):
	id = models.BigAutoField(primary_key=True)
	# account_id = models.BigIntegerField(unique=True)
	smerpaccount = models.OneToOneField(SmerpAccount, db_column="account_id", related_name="smerperpinfo", to_field='id')

	full_name = models.CharField(unique=True, max_length=64, verbose_name=u"企业全称")
	organization_code = models.CharField(max_length=32, verbose_name=u"组织机构代码")
	registration_no = models.CharField(max_length=32, verbose_name=u"工商执照注册号")
	representative = models.CharField(max_length=32, verbose_name=u"法人")
	scope_normal = models.TextField(blank=True, null=True, verbose_name=u"一般经营范围")
	scope_sepcial = models.TextField(blank=True, null=True, verbose_name=u"前置许可经营范围")
	staff_num = models.IntegerField(verbose_name=u"企业规模")
	licence_img = models.CharField(max_length=200, verbose_name=u"营业执照")
	manager = models.CharField(max_length=32, verbose_name=u"管理员")
	manager_phone = models.CharField(max_length=16, verbose_name=u"管理员手机号")
	manager_id_card_no = models.CharField(max_length=32, verbose_name=u"管理员身份证")
	manager_id_card_img = models.CharField(max_length=128, verbose_name=u"管理员身份证图片")

	check_status = models.IntegerField(choices=CHECK_STATUS_CHOICES, verbose_name=u"审核状态")
	create_time = models.DateTimeField(verbose_name=u"创建时间")
	submit_check_time = models.DateTimeField(blank=True, null=True, verbose_name=u"提交审核时间")
	check_mark = models.CharField(max_length=512, blank=True, null=True, verbose_name=u"审核说明")
	check_time = models.DateTimeField(blank=True, null=True, verbose_name=u"审核时间")

	class Meta:
		managed = False
		db_table = 'smerp_erpinfo'


class SmerpMaterial(models.Model):
	id = models.BigAutoField(primary_key=True)
	# account_id = models.BigIntegerField()
	smerpaccount = models.ForeignKey(SmerpAccount, db_column="account_id", related_name="smerpmaterials", to_field='id')

	name = models.CharField(max_length=64, verbose_name=u"原料名称")
	producer = models.CharField(max_length=64, verbose_name=u"产地")
	source_type = models.CharField(max_length=16, verbose_name=u"来源")
	ref_image = models.CharField(max_length=128, blank=True, null=True, verbose_name=u"参考图")
	ref_url = models.CharField(max_length=128, blank=True, null=True, verbose_name=u"参考资料地址")
	create_time = models.DateTimeField(verbose_name=u"创建时间")

	class Meta:
		managed = False
		db_table = 'smerp_material'


class SmerpProduct(models.Model):
	id = models.BigAutoField(primary_key=True)
	# account_id = models.BigIntegerField()
	smerpaccount = models.ForeignKey(SmerpAccount, db_column="account_id", related_name="smerpproducts", to_field='id')

	# brand_id = models.BigIntegerField()
	smerpbrand = models.ForeignKey(SmerpBrand, db_column="brand_id", related_name="smerpproducts", to_field='id')

	name = models.CharField(max_length=64, verbose_name=u"产品名称")
	check_status = models.IntegerField(choices=CHECK_STATUS_CHOICES, verbose_name=u"审核状态")
	create_time = models.DateTimeField(verbose_name=u"创建时间")

	smerpmaterials = models.ManyToManyField(SmerpMaterial, related_name="smerpproducts", through='SmerpProductMaterial', through_fields=('smerpproduct', 'smerpmaterial'))

	submit_check_time = models.DateTimeField(blank=True, null=True, verbose_name=u"提交审核时间")
	check_mark = models.CharField(max_length=512, blank=True, null=True, verbose_name=u"审核说明")
	check_time = models.DateTimeField(blank=True, null=True, verbose_name=u"审核时间")

	class Meta:
		managed = False
		db_table = 'smerp_product'


class SmerpProductMaterial(models.Model):
	id = models.BigAutoField(primary_key=True)
	# product_id = models.BigIntegerField()
	# material_id = models.BigIntegerField()

	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="smerpproducts", to_field='id')
	smerpmaterial = models.ForeignKey(SmerpMaterial, db_column="material_id", related_name="smerpproductmaterials", to_field='id')

	class Meta:
		managed = False
		db_table = 'smerp_product_material'


class SmerpProductImg(models.Model):
	id = models.BigAutoField(primary_key=True)
	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="smerpproductimgs", to_field='id')

	img = models.CharField(max_length=128)
	create_time = models.DateTimeField()

	class Meta:
		managed = False
		db_table = 'smerp_product_img'


class SmerpProductLicense(models.Model):
	id = models.BigAutoField(primary_key=True)
	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="smerpproductlicenses", to_field='id')

	name = models.CharField(max_length=32)
	type = models.CharField(max_length=32)
	img = models.CharField(max_length=128)
	effect_time = models.DateTimeField(blank=True, null=True)
	expire_time = models.DateTimeField(blank=True, null=True)
	create_time = models.DateTimeField(blank=True, null=True)

	class Meta:
		managed = False
		db_table = 'smerp_product_license'


class SmerpPublishSmcodeLog(models.Model):
	id = models.BigAutoField(primary_key=True)
	# account_id = models.BigIntegerField()
	smerpaccount = models.ForeignKey(SmerpAccount, db_column="account_id", related_name="smerppublishsmcodelogs", to_field='id')

	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="smerppublishsmcodelogs", to_field='id')

	num = models.BigIntegerField()
	start_no = models.BigIntegerField()
	end_no = models.BigIntegerField()
	price = models.FloatField()
	province = models.CharField(max_length=64)
	create_time = models.DateTimeField()

	class Meta:
		managed = False
		db_table = 'smerp_publish_smcode_log'


class SmerpSmcodeOrder(models.Model):
	id = models.BigIntegerField(primary_key=True)
	order_id = models.CharField(unique=True, max_length=32, verbose_name=u"订单号")

	# account_id = models.BigIntegerField()
	smerpaccount = models.ForeignKey(SmerpAccount, db_column="account_id", related_name="smerpsmcodeorders", to_field='id', verbose_name=u"企业")

	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="smerpsmcodeorders", to_field='id', verbose_name=u"产品")

	num = models.BigIntegerField(verbose_name=u"溯码数量")
	goods_desc = models.CharField(max_length=64, verbose_name=u"商品描述")
	goods_amount = models.BigIntegerField(verbose_name=u"商品份数")
	pay_type = models.CharField(max_length=32, verbose_name=u"付款方式")
	pay_status = models.IntegerField(verbose_name=u"付款状态")
	pay_time = models.DateTimeField(blank=True, null=True, verbose_name=u"付款时间")
	bank_order_id = models.CharField(max_length=64, blank=True, null=True, verbose_name=u"银行订单号")
	add_code_status = models.IntegerField(verbose_name=u"增加溯码状态")
	ext = models.CharField(max_length=512, verbose_name=u"扩展数据")
	create_time = models.DateTimeField(blank=True, null=True, verbose_name=u"订单时间")

	class Meta:
		managed = False
		db_table = 'smerp_smcode_order'


class SmerpSmcode(models.Model):
	id = models.BigAutoField(primary_key=True)
	# order_id = models.CharField(unique=True, max_length=64)
	smerpsmcodeorder = models.OneToOneField(SmerpSmcodeOrder, db_column="order_id", related_name="smerpsmcode", to_field='order_id')

	# account_id = models.BigIntegerField()
	smerpaccount = models.ForeignKey(SmerpAccount, db_column="account_id", related_name="smerpsmcodes", to_field='id')

	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="smerpsmcodes", to_field='id')

	num = models.CharField(max_length=255)
	start_no = models.BigIntegerField()
	end_no = models.BigIntegerField()
	publish_num = models.BigIntegerField()
	publish_end_no = models.BigIntegerField()
	create_time = models.DateTimeField()

	class Meta:
		managed = False
		db_table = 'smerp_smcode'


class WxmpAbnormalLog(models.Model):
	id = models.BigAutoField(primary_key=True)
	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="wxmpabnormallogs", to_field='id')
	smcode_no = models.BigIntegerField(verbose_name=u"溯码序号")
	scan_count = models.IntegerField(verbose_name=u"扫码次数")
	type = models.CharField(max_length=32, verbose_name=u"类型")
	mark = models.CharField(max_length=128, blank=True, null=True, verbose_name=u"备注")
	create_time = models.DateTimeField(verbose_name=u"时间")

	class Meta:
		managed = False
		db_table = 'wxmp_abnormal_log'
		unique_together = (('smerpproduct', 'smcode_no'),)


class WxmpBuyer(models.Model):
	id = models.BigAutoField(primary_key=True)
	openid = models.CharField(max_length=64, verbose_name=u"openid")
	nickname = models.CharField(max_length=32, verbose_name=u"昵称")
	head_img = models.CharField(max_length=256, verbose_name=u"头像")
	province = models.CharField(max_length=32, verbose_name=u"省")
	city = models.CharField(max_length=32, verbose_name=u"城市")
	sex = models.IntegerField(verbose_name=u"性别")
	create_time = models.DateTimeField(verbose_name=u"时间")

	class Meta:
		managed = False
		db_table = 'wxmp_buyer'


class WxmpConfig(models.Model):
	id = models.BigAutoField(primary_key=True, verbose_name=u"Id")
	name = models.CharField(max_length=64, verbose_name=u"参数名")
	value = models.TextField(blank=True, null=True, verbose_name=u"参数值")
	vtype = models.CharField(max_length=16, verbose_name=u"值类型")
	label = models.CharField(max_length=64, verbose_name=u"标题")
	description = models.TextField(blank=True, null=True, verbose_name=u"描述")
	input_options = models.TextField(verbose_name=u"输入框配置")
	update_time = models.DateTimeField(blank=True, null=True, verbose_name=u"更新时间")

	class Meta:
		managed = False
		db_table = 'wxmp_config'


class WxmpFeedback(models.Model):
	id = models.BigAutoField(primary_key=True)
	buyer_id = models.BigIntegerField()
	buyer_name = models.CharField(max_length=32, verbose_name=u"购买者")
	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="wxmpfeedbacks", to_field='id')

	type = models.CharField(max_length=32, verbose_name=u"类型")
	content = models.CharField(max_length=512, verbose_name=u"反馈内容")
	create_time = models.DateTimeField(verbose_name=u"反馈时间")

	class Meta:
		managed = False
		db_table = 'wxmp_feedback'


class WxmpScanLog(models.Model):
	id = models.BigAutoField(primary_key=True)
	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="wxmpscanlogs", to_field='id')
	smcode_no = models.BigIntegerField(verbose_name=u"序号")
	product_name = models.CharField(max_length=64, verbose_name=u"产品名称")
	buyer_id = models.BigIntegerField()
	buyer_name = models.CharField(max_length=32, verbose_name=u"购买者")
	publish_price = models.FloatField(verbose_name=u"发布价格")
	publish_province = models.CharField(max_length=64, verbose_name=u"发布省份")
	publish_time = models.DateTimeField(blank=True, null=True, verbose_name=u"发布时间")
	scan_province = models.CharField(max_length=64, verbose_name=u"扫码省份")
	scan_city = models.CharField(max_length=64, verbose_name=u"扫码城市")
	scan_location = models.CharField(max_length=256, verbose_name=u"扫码位置")
	scan_ptype = models.CharField(max_length=64, verbose_name=u"手机型号")
	scan_os = models.CharField(max_length=32, verbose_name=u"系统")
	scan_browser = models.CharField(max_length=64, verbose_name=u"浏览器")
	scan_ip = models.CharField(max_length=32, verbose_name=u"IP")
	create_time = models.DateTimeField()

	class Meta:
		managed = False
		db_table = 'wxmp_scan_log'


class WxmpScanNumDayReport(models.Model):
	id = models.BigIntegerField(primary_key=True)
	day_time = models.DateField(verbose_name=u"日期")
	# product_id = models.BigIntegerField()
	smerpproduct = models.ForeignKey(SmerpProduct, db_column="product_id", related_name="wxmpscannumdayreports", to_field='id')
	num = models.IntegerField(verbose_name=u"扫描次数")

	class Meta:
		managed = False
		db_table = 'wxmp_scan_num_day_report'
		unique_together = (('day_time', 'smerpproduct'),)


class SmplatConfig(models.Model):
	id = models.BigAutoField(primary_key=True, verbose_name=u"Id")
	name = models.CharField(max_length=64, verbose_name=u"参数名")
	value = models.TextField(blank=True, null=True, verbose_name=u"参数值")
	vtype = models.CharField(max_length=16, verbose_name=u"值类型")
	label = models.CharField(max_length=64, verbose_name=u"标题")
	description = models.TextField(blank=True, null=True, verbose_name=u"描述")
	input_options = models.TextField(verbose_name=u"输入框配置")
	update_time = models.DateTimeField(blank=True, null=True, verbose_name=u"更新时间")

	class Meta:
		managed = False
		db_table = 'smplat_config'


class SmadminConfig(models.Model):
	id = models.BigAutoField(primary_key=True, verbose_name=u"Id")
	name = models.CharField(max_length=64, verbose_name=u"参数名")
	value = models.TextField(blank=True, null=True, verbose_name=u"参数值")
	vtype = models.CharField(max_length=16, verbose_name=u"值类型")
	label = models.CharField(max_length=64, verbose_name=u"标题")
	description = models.TextField(blank=True, null=True, verbose_name=u"描述")
	input_options = models.TextField(verbose_name=u"输入框配置")
	update_time = models.DateTimeField(blank=True, null=True, verbose_name=u"更新时间")

	class Meta:
		managed = False
		db_table = 'smadmin_config'
